package com.luoran.bartalks.api;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.annotation.OperationLog;
import com.luoran.bartalks.core.AppUser;
import com.luoran.bartalks.entity.biz.BtContainer;
import com.luoran.bartalks.entity.biz.BtMateriel;
import com.luoran.bartalks.entity.biz.BtPackingListMateriel;
import com.luoran.bartalks.entity.biz.BtPlanBiz;
import com.luoran.bartalks.entity.biz.BtPlanEntry;
import com.luoran.bartalks.service.IBtContainerService;
import com.luoran.bartalks.service.IBtMaterielService;
import com.luoran.bartalks.service.IBtPackingListMaterielService;
import com.luoran.bartalks.service.IBtPackingListService;
import com.luoran.bartalks.service.IBtPlanBizService;
import com.luoran.bartalks.service.IBtPlanEntryService;
import com.luoran.bartalks.utils.EnumOperationType;

@RestController
@RequestMapping("/api/Unload")
public class UnloadApi {

	@Autowired
	private IBtContainerService iBtContainerService;
	@Autowired
	private IBtPlanBizService iBtPlanBizService;
	@Autowired
	private IBtMaterielService iBtMaterielService;
	@Autowired
	private IBtPackingListMaterielService packingListMaterielService;
	@Autowired
	private IBtPlanEntryService planEntryService;
	@Autowired
	private IBtPackingListService packingListService;

	private static final Logger log = LoggerFactory.getLogger(UnloadApi.class);

	// 卸货 扫描容器
	@RequestMapping("ScanContainer")
	public JSONObject ScanContainer(String qrcode, String planpositionId, String planId) {
		JSONObject res = new JSONObject();
		// qrcode校验
		if (StringUtils.isEmpty(qrcode)) {
			res.put("state", false);
			res.put("msg", "无效二维码,请重新扫描!");
			return res;
		}
		// 获得上一个点的planpositionId
		/*
		 * BtPlanEntry BtPlanEntryCurrent =
		 * iBtPlanEntryService.getPlanEntryById(planpositionId); BtPlanEntry
		 * BtPlanEntryPrevious = iBtPlanEntryService.getPlanEntryByPlanIdAndSign(planId,
		 * AppUser.get().getCompanyId(), BtPlanEntryCurrent.getSign() - 1); String
		 * planPositionId = BtPlanEntryPrevious.getId();
		 */
		// 需要根据容器二维码和公司ID 校验容器
		BtContainer btContainer = iBtContainerService.getContainerByQrcodeAndCompanyId(qrcode,
				AppUser.get().getCompanyId());
		if (btContainer != null) {
			res.put("containerID", btContainer.getId());// ID
			res.put("containerCode", btContainer.getContainerCode());// 编码
			if (btContainer.getContainerType() == 0) {
				res.put("containerType", "仓储容器");// 类型
			} else if (btContainer.getContainerType() == 1) {
				res.put("containerType", "运输容器");// 类型
			} else {
				res.put("containerType", "未定义容器");// 类型
			}
			res.put("containerName", btContainer.getContainerName());// 名称
			res.put("containerBearWeight", btContainer.getBearWeight());// 承重
			res.put("containerDeadWeight", btContainer.getDeadWeight());// 自重
			res.put("containerHigh", btContainer.getHigh());// 高
			res.put("containerLong", btContainer.getLongs());// 长
			res.put("containerWide", btContainer.getWide());// 宽
			res.put("containerPermission", btContainer.getPermission());// 容器许可
			res.put("containerComment", btContainer.getComment());// 备注
			res.put("state", true);
		} else {
			res.put("state", false);
			res.put("msg", "请扫描正确的二维码");
		}
		return res;
	}

	/*
	 * // 选择容器
	 * 
	 * @RequestMapping("ChoseContainers") public JSONObject ChoseContainers() {
	 * JSONObject res = new JSONObject(); List<BtContainer> containers =
	 * iBtContainerService.getContainerBycompanyId(AppUser.get().getCompanyId());
	 * res.put("data", containers); return res; }
	 */

	// 卸货=>货物扫描
	@RequestMapping("ScanMateriel")
	public JSONObject UnloadontainerScan(String planId, String qrcode, String containerId, String planpositionId,
			String projectId) {
		JSONObject res = new JSONObject();
		// qrcode校验
		if (StringUtils.isEmpty(qrcode)) {
			res.put("state", false);
			res.put("msg", "无效二维码,请重新扫描!");
			return res;
		}
		// 获取容器信息
		BtContainer container = iBtContainerService.getContainerById(containerId);
		// (获得上一个点的planPositionId)
		BtPlanEntry BtPlanEntryCurrent = planEntryService.getPlanEntryById(planpositionId);
		BtPlanEntry BtPlanEntryPrevious = planEntryService.getPlanEntryByPlanIdAndSign(planId,
				AppUser.get().getCompanyId(), BtPlanEntryCurrent.getSign() - 1);
		String planPositionId = BtPlanEntryPrevious.getId();
		// 根据二维码校验
		BtPackingListMateriel packingListMateriel = packingListMaterielService
				.getItemByMaterielQrcodeAndCompanyId(qrcode, AppUser.get().getCompanyId());
		if (packingListMateriel != null) {
			String planPkgMaterielId = packingListMateriel.getId();

			// 根据箱单物料id,查询当前点该物料是否存在装货记录,有就跳过,没有添加 .避免重复扫描重复添加
			BtPlanBiz persistentPlanBiz = iBtPlanBizService
					.getItemByPackingListMaterielIdAndPlanPositionId(planPkgMaterielId, planpositionId, 10);
			if (persistentPlanBiz == null) {
				// 查询是否是该计划上一点的物料
				BtPlanBiz BtplanBiz = iBtPlanBizService.findmaterielByPlanpositionIdAndplanId(planId,
						packingListMateriel.getMaterielId(), planPositionId);
				// 非上一地点已装则视为异常信息处理 并自动上报
				if (BtplanBiz == null) {
					// 因为无法判断 哪里卸货的 所以只要装载到目标容器中
					BtPlanBiz btPlanBiznew = new BtPlanBiz();
					btPlanBiznew.setProjectId(projectId);
					btPlanBiznew.setPlanId(planId);
					btPlanBiznew.setMaterielId(packingListMateriel.getMaterielId());
					btPlanBiznew.setMaterielName(packingListMateriel.getMaterielName());
					btPlanBiznew.setContainerId(containerId);
					btPlanBiznew.setBizType(10);
					btPlanBiznew.setBizDate(new Date());
					btPlanBiznew.setBizUser(AppUser.get().getId());
					btPlanBiznew.setPlanPositionId(planpositionId);
					btPlanBiznew.setPlanPkgMaterielId(planPkgMaterielId);
					LoadPlanBiz(btPlanBiznew);
					// 判断是否是计划中的货物
					int check = packingListService.checkByPackingListIdAndPlanId(packingListMateriel.getPackingListId(),
							planId, AppUser.get().getCompanyId());
					// 非该计划货物但是同公司下的可以捎带,自动上报异常,
					if (check == 0) {
						// 自动异常上报
						String exception = planEntryService.getPlanEntryById(planPositionId).getException();
						if (exception == null) {
							exception = "";
						}
						planEntryService.updateExceptionInfo(planPositionId, planId,
								exception + "\n编码为:" + packingListMateriel.getMaterielCode() + " 的"
										+ packingListMateriel.getMaterielName() + "不是计划中的货物,但是在"
										+ planEntryService.getPlanEntryById(planPositionId).getAddressName() + "装载至编码为:"
										+ container.getContainerCode() + "的" + container.getContainerName() + "中");
					} else {
						// 是该计划的货物但是不是从上一点装来的
						// 自动异常上报
						String exception = planEntryService.getPlanEntryById(planpositionId).getException();
						if (exception == null) {
							exception = "";
						}
						planEntryService.updateExceptionInfo(planpositionId, planId,
								exception + "\n编码为:" + packingListMateriel.getMaterielCode() + " 的"
										+ packingListMateriel.getMaterielName() + "装卸货地点异常");
						// 这里标识false为只有装货 true为装卸货都有可能(可能出现2种情况)
						res.put("bizTag", false);
					}
				} else {
					// 是上一地点的物料
					// 从原来容器中卸载
					BtPlanBiz btPlanBizold = new BtPlanBiz();
					btPlanBizold.setProjectId(BtplanBiz.getProjectId());
					btPlanBizold.setPlanId(BtplanBiz.getPlanId());
					btPlanBizold.setMaterielId(BtplanBiz.getMaterielId());
					btPlanBizold.setMaterielName(BtplanBiz.getMaterielName());
					btPlanBizold.setContainerId(BtplanBiz.getContainerId());
					btPlanBizold.setBizType(20);
					btPlanBizold.setBizDate(new Date());
					btPlanBizold.setBizUser(AppUser.get().getId());
					btPlanBizold.setPlanPositionId(planpositionId);
					btPlanBizold.setPlanPkgMaterielId(planPkgMaterielId);
					unloadPlanBiz(btPlanBizold);
					// 装载到目标容器中
					BtPlanBiz btPlanBiznew = new BtPlanBiz();
					btPlanBiznew.setProjectId(BtplanBiz.getProjectId());
					btPlanBiznew.setPlanId(BtplanBiz.getPlanId());
					btPlanBiznew.setMaterielId(BtplanBiz.getMaterielId());
					btPlanBiznew.setMaterielName(BtplanBiz.getMaterielName());
					btPlanBiznew.setContainerId(containerId);
					btPlanBiznew.setBizType(10);
					btPlanBiznew.setBizDate(new Date());
					btPlanBiznew.setBizUser(AppUser.get().getId());
					btPlanBiznew.setPlanPositionId(planpositionId);
					btPlanBiznew.setPlanPkgMaterielId(planPkgMaterielId);
					LoadPlanBiz(btPlanBiznew);
					// 只有装货 true为装卸货都有可能(可能出现2种情况)
					res.put("bizTag", true);
				}
			} else {
				// 查找当前点有没有卸货记录
				BtPlanBiz planBizOfload = iBtPlanBizService
						.getItemByPackingListMaterielIdAndPlanPositionId(planPkgMaterielId, planpositionId, 20);
				if (planBizOfload == null) {
					res.put("bizTag", false);
				} else {
					res.put("bizTag", true);
				}
			}
			// 展示物料信息
			BtMateriel btMateriel = iBtMaterielService.getBtMateriel(packingListMateriel.getMaterielId());
			res.put("materielId", btMateriel.getId());// ID
			res.put("materielCode", btMateriel.getMaterielCode());// 编码
			res.put("materielName", btMateriel.getMaterielName());// 名称
			res.put("materielEmptyWeight", btMateriel.getEmptyWeight());// 净重
			res.put("materielGrossWeight", btMateriel.getGrossWeight());// 毛重
			res.put("materielLength", btMateriel.getLength());// 长
			res.put("materielWidth", btMateriel.getWidth());// 宽
			res.put("materielHeight", btMateriel.getHeight());// 高

			res.put("takePhoto", packingListMateriel.getTakePhoto());// 强制拍照

			// 展示容器信息
			res.put("containerID", container.getId());// ID
			res.put("containerCode", container.getContainerCode());// 编码
			if (container.getContainerType() == 0) {
				res.put("containerType", "仓储容器");// 类型
			} else if (container.getContainerType() == 1) {
				res.put("containerType", "运输容器");// 类型
			} else {
				res.put("containerType", "未定义容器");// 类型
			}
			res.put("containerName", container.getContainerName());// 名称
			res.put("containerBearWeight", container.getBearWeight());// 承重
			res.put("containerDeadWeight", container.getDeadWeight());// 自重
			res.put("containerHigh", container.getHigh());// 高
			res.put("containerLong", container.getLongs());// 长
			res.put("containerWide", container.getWide());// 宽
			res.put("containerPermission", container.getPermission());// 容器许可
			res.put("containerComment", container.getComment());// 备注
			// 获取该容器下的应卸物料条数(上一点已装)
			int MaterielByContainerNumberIn = iBtPlanBizService.getInedItemCountByContainer(planPositionId, planId,
					containerId);
			res.put("materielNumberIn", MaterielByContainerNumberIn);
			// 获取该容器下的已卸载物料条数(此点该容器已装)
			int MaterielByContainerNumberOut = iBtPlanBizService.getInedItemCountByContainer(planpositionId, planId,
					containerId);
			res.put("materielNumberOut", MaterielByContainerNumberOut);
			// 当前点已卸的物料列表(此点该容器已装)
			List<BtPlanBiz> BtPlanBizOut = iBtPlanBizService.getInedItemInfoCountByContainer(planpositionId, planId,
					containerId);
			// 获取已经装载重量与体积
			if (BtPlanBizOut.size() != 0) {
				BigDecimal MaterielgrossWeightSum = new BigDecimal(0);
				BigDecimal MaterielvolumeSum = new BigDecimal(0);
				for (BtPlanBiz btPlanBizOut : BtPlanBizOut) {
					BtMateriel materiel = iBtMaterielService.getBtMateriel(btPlanBizOut.getMaterielId());
					MaterielgrossWeightSum = MaterielgrossWeightSum.add(materiel.getEmptyWeight());
					MaterielvolumeSum = MaterielvolumeSum.add(materiel.getLength().multiply(materiel.getWidth())
							.multiply(materiel.getHeight().setScale(6, BigDecimal.ROUND_HALF_UP)));// 体积
				}
				// 保留3位小数,四舍五入
				res.put("MaterielvolumeSum", MaterielvolumeSum);
				res.put("containerbearweightNow", MaterielgrossWeightSum);
			}
			res.put("state", true);
		} else {
			res.put("state", false);
			res.put("msg", "请扫描正确的货物二维码!");
		}
		return res;
	}

	@OperationLog(EnumOperationType.LOADING)
	private String LoadPlanBiz(BtPlanBiz PlanBiz) {
		JSONObject json = new JSONObject();
		try {
			iBtPlanBizService.addPlanBiz(PlanBiz);
			json.put("state", true);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("state", false);
		}
		return json.toJSONString();
	}
	
	@OperationLog(EnumOperationType.UNLOAD)
	private String unloadPlanBiz(BtPlanBiz PlanBiz) {
		JSONObject json = new JSONObject();
		try {
			iBtPlanBizService.addPlanBiz(PlanBiz);
			json.put("state", true);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("state", false);
		}
		return json.toJSONString();
	}
	
	
	// 一键卸货
	@RequestMapping("UnloadMaterielAll")
	public JSONObject UnloadMaterielAll(String planId, String containerId, String planpositionId) {
		log.info("使用一键卸货卸载计划id为" + planId + "在planpositionId为" + planpositionId + "的容器id为" + containerId + "中的货物");
		JSONObject res = new JSONObject();
		// (获得上一个点的planPositionId)
		BtPlanEntry BtPlanEntryCurrent = planEntryService.getPlanEntryById(planpositionId);
		BtPlanEntry BtPlanEntryPrevious = planEntryService.getPlanEntryByPlanIdAndSign(planId,
				AppUser.get().getCompanyId(), BtPlanEntryCurrent.getSign() - 1);
		String planPositionId = BtPlanEntryPrevious.getId();
		// 获取该容器下的应卸物料条数(上一个点已装)
		int MaterielByContainerNumberIn = iBtPlanBizService.getInedItemCountByContainer(planPositionId, planId,
				containerId);
		// 获取该容器下的已卸载物料条数
		int MaterielByContainerNumberOut = iBtPlanBizService.getOutedItemCountByContainer(planpositionId, planId,
				containerId);
		if (MaterielByContainerNumberIn <= MaterielByContainerNumberOut) {
			res.put("msg", "该容器中的货物已经全部卸载完成了!");
			res.put("repeat", true);
		} else {
			// 删除手动扫描的当前点已卸的物料列表
			List<BtPlanBiz> BtPlanBiz2 = iBtPlanBizService.getOutedItemInfoCountByContainer(planpositionId, planId,
					containerId);
			for (BtPlanBiz btPlanBiz : BtPlanBiz2) {
				iBtPlanBizService.deleteOutedItemInfoCountByContainer(btPlanBiz.getId());
			}
			// 当前点应卸的物料列表(上一点已装)
			List<BtPlanBiz> BtPlanBiz1 = iBtPlanBizService.getInedItemInfoCountByContainer(planPositionId, planId,
					containerId);
			for (BtPlanBiz btPlanBiz1 : BtPlanBiz1) {
				BtPlanBiz btPlanBiz = new BtPlanBiz();
				btPlanBiz.setProjectId(btPlanBiz1.getProjectId());
				btPlanBiz.setPlanId(btPlanBiz1.getPlanId());
				btPlanBiz.setMaterielId(btPlanBiz1.getMaterielId());
				btPlanBiz.setMaterielName(btPlanBiz1.getMaterielName());
				btPlanBiz.setContainerId(btPlanBiz1.getContainerId());
				btPlanBiz.setBizType(20);
				btPlanBiz.setBizDate(new Date());
				btPlanBiz.setBizUser(btPlanBiz1.getBizUser());
				btPlanBiz.setPlanPositionId(planpositionId);
				iBtPlanBizService.addPlanBiz(btPlanBiz);
			}
			// 重新获取装载信息
			// 获取该容器下的应卸物料条数(上一个点已装)
			int MaterielByContainerNumberIn2 = iBtPlanBizService.getInedItemCountByContainer(planPositionId, planId,
					containerId);
			// 获取该容器下的已卸载物料条数
			int MaterielByContainerNumberOut2 = iBtPlanBizService.getOutedItemCountByContainer(planpositionId, planId,
					containerId);
			res.put("materielNumberIn", MaterielByContainerNumberIn2);
			res.put("materielNumberOut", MaterielByContainerNumberOut2);
			// 当前点已卸的物料列表
			List<BtPlanBiz> BtPlanBiz3 = iBtPlanBizService.getOutedItemInfoCountByContainer(planpositionId, planId,
					containerId);
			// 获取已经装载重量
			if (BtPlanBiz3.size() != 0) {
				BigDecimal MaterielgrossWeightSum = new BigDecimal(0);
				for (BtPlanBiz btPlanBiz1 : BtPlanBiz3) {
					BigDecimal emptyWeight = iBtMaterielService.getBtMateriel(btPlanBiz1.getMaterielId())
							.getEmptyWeight();
					MaterielgrossWeightSum = MaterielgrossWeightSum.add(emptyWeight);
				}
				// 保留3位小数,四舍五入
				res.put("containerbearweightNow", MaterielgrossWeightSum.setScale(3, BigDecimal.ROUND_HALF_UP));
				res.put("containerbearweightPlan", iBtContainerService.getContainerById(containerId).getBearWeight());
			}
			res.put("msg", "一键卸货完成!");
			res.put("state", true);
		}

		return res;
	}

}
